<template>
    <img class="oauth-login" :src="githubImg" v-if="!signState" @click="saveURL"/>
    <img class="oauth-login" :src="exitImg" v-else @click="logout"/>

</template>

<script>
    export default {
        name: "github",
        data() {
            return {
                client_id: 'e02592feaf146ba5eeb8',
                client_secret: '4a32269a5548f87e0cf70c771eac52a60394f1f5',
                scope: 'read:user', // Grants access to read a user's profile data.
                state: '',
                getCodeURL: 'https://github.com/login/oauth/authorize',
                getAccessTokenURL: '/github/login/oauth/access_token',
                getUserURl: 'https://api.github.com/user',
                redirectURL: null,
                code: null,
                accessToken: null,
                signState: false,
                githubImg: "http://111.231.239.202:8018/data/img/project/github.png",
                exitImg: "http://111.231.239.202:8018/data/img/project/exit.png"
            }
        },
        created() {
            //尝试获取地址栏中的code
            this.getGitCode();
            if (this.code) {
                //存在code
                this.accessToken = this.$cookie.get('accessToken');
                if (this.accessToken) {
                    //获取用户
                    this.getUser()
                } else {
                    // url中存在code 但是cookie中没有 令牌 => 根据code向 github取 令牌
                    this.getAccessToken();
                }
            }
        },
        methods: {
            saveURL() {
                //设置重定向URL
                this.$cookie.set('redirectURL', location.href, 1);
                //域名重定向 获取code
                location.href = this.getCodeURL;
            },
            logout() {
                this.$cookie.delete('accessToken');
                this.signState = false;
                //触发用户登出事件
                this.$emit('logoutEvent')
            },
            getGitCode() {
                this.getCodeURL += ('?' + this.$qs.stringify({
                    client_id: this.client_id,
                    scope: this.scope,
                    state: this.state
                }));
                let parse = this.$qs.parse(location.search.replace("?", ""));
                if (parse.state === this.state) {
                    this.code = parse.code
                }
            },
            getAccessToken() {
                this.$axios.post(this.getAccessTokenURL, {
                    client_id: this.client_id,
                    client_secret: this.client_secret,
                    code: this.code,
                    state: this.state
                }).then((response) => {
                    let result = this.$qs.parse(response.data);
                    //转换github回传的accessToken
                    if (result.error) {
                        console.log(result.error);
                        return;
                    }
                    this.accessToken = result.access_token;
                    if (this.accessToken) {
                        // save to cookie 30 days
                        this.$cookie.set('accessToken', this.accessToken, 30);
                        /*this.redirectURL = this.$cookie.get('redirectURL');
                        if (this.redirectURL) {
                            location.href = this.redirectURL
                        }*/
                        //根据accessToken获取用户
                        this.getUser();


                    }
                })
            },
            getUser() {
                this.$axios.get(this.getUserURl + '?access_token=' + this.accessToken)
                    .then((response) => {
                        let data = response.data;
                        this.signState = true;
                        this.$router.push('/dashboard');
                        // call parent login event
                        this.$emit('loginEvent', {
                            thirdId: data.id,
                            login: data.login,
                            name: data.name,
                            bio: data.bio,
                            avatar: data.avatar_url
                        });
                    })
                    // invaild accessToken
                    .catch((error) => {
                        console.log(error);
                        this.$cookie.delete('accessToken')
                    })
            }
        },
        computed: {
            formatCodeURL() {
                return this.getCodeURL + ('?' + this.$qs.stringify({
                    client_id: this.client_id,
                    scope: this.scope,
                    state: this.state
                }))
            }
        }

    }
</script>

<style scoped>
    .oauth-login {
        cursor: pointer;
        height: 25px;
        width: 25px;
    }
</style>